package com.example.littleken.ormlite_text.Activity;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.SearchView;
import android.widget.Toast;

import com.example.littleken.ormlite_text.R;
import com.example.littleken.ormlite_text.Utils.Utils;
import com.example.littleken.ormlite_text.adapter.lifediaryListViewAdapter;
import com.example.littleken.ormlite_text.bean.LifeDiary;
import com.example.littleken.ormlite_text.db.DatabaseHelper;
import com.j256.ormlite.dao.Dao;

import java.io.Serializable;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import static com.example.littleken.ormlite_text.Utils.Utils.checkState;

/**
 * MainActivity主界面
 */
public class MainActivity extends AppCompatActivity  implements AdapterView.OnItemClickListener,AdapterView.OnItemLongClickListener,SearchView.OnQueryTextListener{
    //数据连接
    public DatabaseHelper databaseHelper = null;
    public Dao lifediaryDAO = null;
    private Button btn_add;
    private Button btn_delete;
    public ListView lv_lifeDiary;

    //用于保存需要在ListView中显示的日记实体类
    List<LifeDiary>lifeDiaries=null;

    //ListView适配器
    lifediaryListViewAdapter  adapter = null;

    //用于保存单击后出现的dialog中的选项
    String[] dialogItem=null;

    //用于保存多选需要删除的日记实体类
    List<LifeDiary>deleteMoreLifeDiaries = new ArrayList<LifeDiary>();

    //Flag 跳转到lifediaryAddActivity 日记添加Activity
    public static final int GOADDACTIVITY = 666;

    //Flag 跳转到UpdateActivity 日记修改Activity
    public static final int GOUPDATEACTIVITY = 888;

    //Flag 跳转到DeleteActivity 日记删除Activity
    public static final int GODELETEACTIVITY = 999;

    //Flag Bundle由MainActivity到UpdateActivity
    public static final String BUNDLE_MAIN_TO_UPDATE = "bundleformaintoupdate";

    //Flag 比较器使用由大到小排序
    public static final int SORT_BIG_TO_SMALL = 0;

    //Flag 比较器使用由小到大排序
    public static final int SORT_SAMLL_TO_BIG = 1;

    //用于保存目前使用的比较器类型
    int currSort = SORT_BIG_TO_SMALL;

    //比较器
    Comparator<LifeDiary> currComparator =null;

    //用于保存哪个item被选中
    private boolean[] flags;

    //用于保存是否有item被选中
    private boolean state = false;

    //比较器，用于排序(正序)
    Comparator<LifeDiary> dateComparatorbigtosmall = new Comparator<LifeDiary>() {
        @Override
        public int compare(LifeDiary left, LifeDiary right) {
            Long lefttime = Long.valueOf(left.getCreatetime());
            Long righttime = Long.valueOf(right.getCreatetime());
            if(lefttime.longValue()>righttime.longValue()){
                return 1;
            }else if(lefttime.longValue()<righttime.longValue()) {
                return -1;
            }else {
                return 0;
            }
        }
    };

    //比较器，用于排序(倒序)
    Comparator<LifeDiary> dateComparatorsmalltobig = new Comparator<LifeDiary>() {
        @Override
        public int compare(LifeDiary left, LifeDiary right) {
            Long lefttime = Long.valueOf(left.getCreatetime());
            Long righttime = Long.valueOf(right.getCreatetime());
            if(lefttime.longValue()>righttime.longValue()){
                return -1;
            }else if(lefttime.longValue()<righttime.longValue()) {
                return 1;
            }else {
                return 0;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        try {
            //初始化数据库连接
            lifediaryDAO= Utils.initDb(MainActivity.this);
            initView();
            //初始化lifeDiaries，取得数据库中所有日记信息
            lifeDiaries = lifediaryDAO.queryForAll();
            initItem();//初始化item选中状态
            //初始化适配器
            adapter= new lifediaryListViewAdapter(MainActivity.this);
            adapter.setlifediary(lifeDiaries);
            lv_lifeDiary.setAdapter(adapter);
            lv_lifeDiary.setOnItemClickListener(this);//设置点击事件，点击item触发updateactivity
            lv_lifeDiary.setOnItemLongClickListener(this);//设置长点击事件，触发item选中状态
        } catch (SQLException e) {
            e.printStackTrace();
        }

    }

    private void initView() {
        //初始化点击事件弹出dialog选项
        dialogItem = new String[]{(String) this.getResources().getText(R.string.share),
                (String) this.getResources().getText(R.string.modify),
                (String) this.getResources().getText(R.string.delete)};

        btn_add = (Button) findViewById(R.id.btn_add);
        btn_delete = (Button) findViewById(R.id.btn_delete);
        lv_lifeDiary = (ListView) findViewById(R.id.lv_lifeDiary);

        btn_add.setOnClickListener(new View.OnClickListener() {
           @Override
           public void onClick(View view) {
               go();//跳转到日记添加Activity
           }
       });
        btn_delete.setOnClickListener(new View.OnClickListener() {
           @Override
           public void onClick(View view) {
               //item选中状态判空
               if(deleteMoreLifeDiaries == null || deleteMoreLifeDiaries.size() == 0){
                   Toast.makeText(MainActivity.this,"请先长按选中需要删除的日记",Toast.LENGTH_SHORT).show();
               }else{
                   try {
                       //多条删除
                       deleteMore(deleteMoreLifeDiaries,MainActivity.this);
                   } catch (SQLException e) {
                       e.printStackTrace();
                   }
               }
           }
       });
    }

    /**
     * 日记多条删除
     * @param deleteMoreLifeDiaries 需要删除的日记实体类List
     * @param context 上下文
     * @throws SQLException 数据库错误
     */
    private void deleteMore(final List<LifeDiary>deleteMoreLifeDiaries, final Context context) throws SQLException {
        //弹出询问删除对话框，防止误触
        final AlertDialog.Builder dialog = new AlertDialog.Builder(context);
        dialog.setTitle((String) this.getResources().getText(R.string.deletediary))
                .setMessage((String) this.getResources().getText(R.string.askfordeletediary))
                .setNegativeButton((String) this.getResources().getText(R.string.no),null)
                .setPositiveButton((String) this.getResources().getText(R.string.yes), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        //循环删除需要删除的日记
                        try {
                            for(LifeDiary LD:deleteMoreLifeDiaries){
                                lifediaryDAO.deleteById(LD.getId());

                            }
                            //删除列表清空
                            deleteMoreLifeDiaries.clear();
                            //刷新listView
                          /*  flags = Utils.updateItems(lifeDiaries);*/
                            //刷新listView
                            updateListView();
                            updateListView_sort(currSort);
                            //刷新listView
                            flags = Utils.updateItems(lifeDiaries);
                            //重置有item被选中的状态
                            state=false;
                            Toast.makeText(context,context.getResources().getText(R.string.deletesuccess),Toast.LENGTH_SHORT).show();
                        } catch (SQLException e) {
                            e.printStackTrace();
                        }
                    }
                }).show();

    }
    //标题栏搜索框
    SearchView sv;
    //菜单初始化
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        //反射出menu.xml
        getMenuInflater().inflate(R.menu.menu_main,menu);
       //添加搜索框
        MenuItem search = menu.findItem(R.id.search);

        sv = new SearchView(this);
        //设置搜索框中内容可提交
        search.setActionView(sv);
        //设置提交按钮
        sv.setSubmitButtonEnabled(true);
        //设置输入框提示信息
        sv.setQueryHint((String) this.getResources().getText(R.string.search));
        sv.setOnQueryTextListener(this);
        //设置关闭搜索框刷新
        sv.setOnCloseListener(new SearchView.OnCloseListener() {
            @Override
            public boolean onClose() {
               try{
                   //刷新列表
                   updateListView();
                   updateListView_sort(currSort);
               }catch (Exception e){
                   e.printStackTrace();
               }
                return true;
            }
        });
        return true;
    }

    //菜单点击监听器
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        switch (id){
            //根据用户选择，设置对应排序方法
            case R.id.sort_big_to_small:
               currSort = SORT_BIG_TO_SMALL;
                Toast.makeText(MainActivity.this,(String) this.getResources().getText(R.string.sort_big_to_small),Toast.LENGTH_SHORT).show();
                break;
            case R.id.sort_small_to_big:
                currSort = SORT_SAMLL_TO_BIG;
                Toast.makeText(MainActivity.this,(String) this.getResources().getText(R.string.sort_small_to_big),Toast.LENGTH_SHORT).show();
                break;
            //ListView刷新
            case R.id.refresh:
                try {
                    updateListView();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
                break;
        }
        updateListView_sort(currSort);//刷新列表
        return true;
    }
    //从数据库重新取得数据
    private void updateListView() throws SQLException {
        lifeDiaries = lifediaryDAO.queryForAll();
        KEYWORD = null;//初始化keyword
      /*  adapter.setlifediary(lifeDiaries);
        lv_lifeDiary.setAdapter(adapter);*/
    }

    //根据对应排序方法，刷新ListView
    public void updateListView_sort(int sort){
        if(sort == SORT_BIG_TO_SMALL){
            currComparator = dateComparatorbigtosmall;
        }else if(sort == SORT_SAMLL_TO_BIG){
            currComparator = dateComparatorsmalltobig;
        }
        Collections.sort(lifeDiaries,currComparator);
        adapter.setlifediary(lifeDiaries);
        adapter.notifyDataSetChanged();
    }
    /*
    处理其他Activity返回的消息
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
       switch (requestCode){
           //成功插入日记
           case GOADDACTIVITY:
               if(resultCode == RESULT_OK){
                   try {
                       //初始化item选中状态
                       //刷新listView
                       flags = Utils.updateItems(lifeDiaries);
                    //刷新列表
                       updateListView();
                       updateListView_sort(currSort);
                       //刷新listView
                      /* flags = Utils.updateItems(lifeDiaries);*/
                   } catch (SQLException e) {
                       e.printStackTrace();
                   }
                   //初始化item选中状态
                   //刷新listView
                   flags = Utils.updateItems(lifeDiaries);
                   Toast.makeText(MainActivity.this,(String) this.getResources().getText(R.string.installsuccess),Toast.LENGTH_SHORT).show();
               }else if (resultCode == RESULT_CANCELED){
                   //初始化item选中状态
                   //刷新listView
                   flags = Utils.updateItems(lifeDiaries);
                   Toast.makeText(MainActivity.this,"日记插入失败",Toast.LENGTH_SHORT).show();
               }
               break;
           //日记更新
           case GOUPDATEACTIVITY:
               if(resultCode == RESULT_OK){
                   try {
                       //初始化item选中状态
                       //刷新listView
                     /*  flags = Utils.updateItems(lifeDiaries);*/
                       updateListView();
                       updateListView_sort(currSort);
                       //初始化item选中状态
                       //刷新listView
                       flags = Utils.updateItems(lifeDiaries);
                   } catch (SQLException e) {
                       e.printStackTrace();
                   }
                   Toast.makeText(MainActivity.this,(String) this.getResources().getText(R.string.updatesuccess),Toast.LENGTH_SHORT).show();
               }else if (resultCode == RESULT_CANCELED){
                   //初始化item选中状态
                   //刷新listView
                   flags = Utils.updateItems(lifeDiaries);
                   Toast.makeText(MainActivity.this,"更新失败",Toast.LENGTH_SHORT).show();
               }
               break;
           //日记删除
           case GODELETEACTIVITY:
                if(resultCode == RESULT_OK){
                    try {
                        updateListView();
                        updateListView_sort(currSort);
                        //初始化item选中状态
                        //刷新listView
                        flags = Utils.updateItems(lifeDiaries);
                    } catch (SQLException e) {
                        e.printStackTrace();
                    }
                }
               break;
       }
    }

    /**
     * 跳转到日记添加Activity
     */
    private void go() {
        startActivityForResult(new Intent(MainActivity.this,lifediaryAddActivity.class),GOADDACTIVITY);
    }

    /**
     * 初始化item选中状态
     */
    private void initItem() {
        flags = new boolean[lifeDiaries.size()];
        for(int i=0;i<lifeDiaries.size();i++){
            flags[i] = false;
        }
    }

    /**
     * item点击事件
     */
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        //获取到本item的实体类
        LifeDiary lifeDiary = (LifeDiary) parent.getItemAtPosition(position);
        RelativeLayout relativeLayout = null;

        //判断item选中状态
        if(!state){
            showClickDialog(lifeDiary);
        }else {
            //触发选中状态
             relativeLayout = (RelativeLayout) view.findViewById(R.id.rlView);
            if(!flags[position]){
                //更新选中状态
              /*  flags[position]=true;
                relativeLayout.setBackgroundColor(Color.BLUE);///////////////////*/
                //判断删除列表中是否已经存在本日记实体类
                if(queryDeleteList(deleteMoreLifeDiaries,lifeDiary)){

                }else {
                    //将本实体类添加到删除列表中
                    deleteMoreLifeDiaries.add(lifeDiary);
                    flags[position]=true;
                    relativeLayout.setBackgroundColor(Color.rgb(0,191,255));
                }
                Log.e("TAG",deleteMoreLifeDiaries.toString());
            }else {
                //更新选中状态
                /*flags[position] = false;
                relativeLayout.setBackgroundColor(Color.WHITE);*/
                if(queryDeleteList(deleteMoreLifeDiaries,lifeDiary)){
                    //将本实体类从删除列表中移除
                    deleteMoreLifeDiaries.remove(lifeDiary);
                    flags[position] = false;
                    relativeLayout.setBackgroundColor(Color.WHITE);
                }else{

                }
                Log.e("TAG",deleteMoreLifeDiaries.toString());
            }
        }
        //更新item选中状态
        state = checkState(flags);
    }

    /**
     *item长点击事件
     */
    @Override
    public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
        //获取到本item的实体类
        LifeDiary lifeDiary = (LifeDiary) parent.getItemAtPosition(position);
        RelativeLayout relativeLayout = (RelativeLayout) view.findViewById(R.id.rlView);

        if(!flags[position]){
            //更新选中状态
           /* flags[position]=true;
            relativeLayout.setBackgroundColor(Color.BLUE);///////////////////*/
            //判断删除列表中是否已经存在本日记实体类
            if(queryDeleteList(deleteMoreLifeDiaries,lifeDiary)){

            }else {
                //将本实体类添加到删除列表中
                deleteMoreLifeDiaries.add(lifeDiary);
                flags[position]=true;
                relativeLayout.setBackgroundColor(Color.rgb(0,191,255));
            }
            Log.e("TAG",deleteMoreLifeDiaries.toString());
        }else {
            //更新选中状态
            /*flags[position] = false;
            relativeLayout.setBackgroundColor(Color.WHITE);*/
            if(queryDeleteList(deleteMoreLifeDiaries,lifeDiary)){
                //将本实体类从删除列表中移除
                deleteMoreLifeDiaries.remove(lifeDiary);
                flags[position] = false;
                relativeLayout.setBackgroundColor(Color.WHITE);
            }else{

            }
            Log.e("TAG",deleteMoreLifeDiaries.toString());
        }
        //更新item选中状态
        state = Utils.checkState(flags);
        return true;
    }
    //用于判断删除列表中是否已经存在删除对象，防止删除两次，触发删除错误
    public boolean queryDeleteList(List<LifeDiary>deleteMoreLifeDiaries,LifeDiary lifeDiary){
        boolean flag = false;
        //循环遍历List寻找是否有对应实体类
        for(LifeDiary lifeDiary1:deleteMoreLifeDiaries){
            if(lifeDiary == lifeDiary1){
                flag = true;
                break;
            }
        }
        return flag;
    }


    //    final String[] dialogItem = {"分享","修改","删除"};
    //Flag 点击事件触发的dialog中的分享
    public static final int DIALOG_SHARE = 0;
    //Flag 点击事件触发的dialog中的修改
    public static final int DIALOG_UPDATE = 1;
    //Flag 点击事件触发的dialog中的删除
    public static final int DIALOG_DELETE = 2;

    /**
     *item点击事件触发的dialog
     */
    public void showClickDialog(final LifeDiary lifeDiary){

       AlertDialog.Builder dialog = new AlertDialog.Builder(MainActivity.this).setTitle(lifeDiary.getTitle())
               .setItems(dialogItem, new DialogInterface.OnClickListener() {
                   @Override
                   public void onClick(DialogInterface dialogInterface, int i) {
                       switch (i){
                           case DIALOG_SHARE:
                               //分享
                               share(lifeDiary);
                               break;
                           case DIALOG_UPDATE:
                             //跳转到修改Activity
                               gotoUpdateActivity(lifeDiary);
                               break;
                           case DIALOG_DELETE:
                               //跳转到删除Activity
                                 gotoDeleteActivity(lifeDiary);
                               break;
                       }
                   }
               });
        dialog.show();
    }

    /**
     * 跳转到更新Activity
     * @param lifeDiary 需要修改的日期实体类
     */
    public void gotoUpdateActivity(LifeDiary lifeDiary){
        Intent intent = new Intent(MainActivity.this,UpdateActivity.class);
        Bundle bundle = new Bundle();
        bundle.putSerializable(BUNDLE_MAIN_TO_UPDATE, (Serializable) lifeDiary);
        intent.putExtras(bundle);
        startActivityForResult(intent,GOUPDATEACTIVITY);
    }

    /**
     * 跳转到删除Activity
     * @param lifeDiary 需要删除的日期实体类
     */
    public void gotoDeleteActivity(LifeDiary lifeDiary){
        Intent intent = new Intent(MainActivity.this,DeleteActivity.class);
        Bundle bundle = new Bundle();
        bundle.putSerializable(BUNDLE_MAIN_TO_UPDATE,(Serializable) lifeDiary);
        intent.putExtras(bundle);
        startActivityForResult(intent,GODELETEACTIVITY);
    }

    /**
     *分享
     */
    public void share(LifeDiary lifeDiary){
        Intent intent = new Intent(Intent.ACTION_SEND);
        intent.setType("text/plain");
        String message = "title:"+lifeDiary.getTitle()+"\nmessage:"+lifeDiary.getMessage();
        intent.putExtra(Intent.EXTRA_TEXT,message);
        startActivity(Intent.createChooser(intent, "分享"));
    }

    //搜索关键字，用于设置高亮
    public static String KEYWORD = null;
    //输入框监听
    @Override
    public boolean onQueryTextSubmit(String key) {//提交监听器
      /*  Toast.makeText(MainActivity.this,key,Toast.LENGTH_SHORT).show();*/
        KEYWORD = key;
        lifeDiaries = Utils.getSearchResult(lifeDiaries,key);
        updateListView_sort(currSort);
        return true;
    }

    @Override
    public boolean onQueryTextChange(String key) {//消息变动监听器

        return true;
    }

}
